const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const fs = require('fs');
const backendService = require('./backendService');
const log = require('./logger');

let mainWindow;
let splashWindow;

// 捕获未处理的异常
process.on('uncaughtException', (error) => {
    log(`Uncaught Exception: ${error.stack}`);
});

process.on('unhandledRejection', (error) => {
    log(`Unhandled Rejection: ${error.stack}`);
});

// 添加启动性能追踪
const startTime = process.hrtime();
function logTimeSince(label) {
    const diff = process.hrtime(startTime);
    const ms = (diff[0] * 1e9 + diff[1]) / 1e6;
    log(`${label}: ${ms.toFixed(1)}ms`);
}

// 优化后端服务检查逻辑
async function checkBackendService(retries = 30, interval = 500) {  // 进一步减少重试次数和间隔
    for (let i = 0; i < retries; i++) {
        try {
            const isRunning = await backendService.checkIfRunning();
            if (isRunning) {
                logTimeSince('Backend service ready');
                return true;
            }
        } catch (error) {
            log(`Backend check attempt ${i + 1}/${retries} failed: ${error.message}`);
        }
        if (i < retries - 1) { // 最后一次不需要等待
            await new Promise(resolve => setTimeout(resolve, interval));
        }
    }
    return false;
}

function createSplashWindow() {
    splashWindow = new BrowserWindow({
        width: 800,
        height: 400,
        frame: false,
        transparent: true,
        // 优化窗口创建配置
        show: false,
        backgroundColor: '#00ffffff',
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            // 启用 GPU 加速
            accelerator: true
        }
    });

    splashWindow.loadFile(path.join(__dirname, 'splash.html'));
    splashWindow.once('ready-to-show', () => {
        splashWindow.show();
        logTimeSince('Splash window shown');
    });
}

function createMainWindow() {
    mainWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        show: false,
        // 优化窗口创建配置
        backgroundColor: '#ffffff',
        autoHideMenuBar: true,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            webSecurity: false,
            preload: path.join(__dirname, 'preload.js'),
            // 启用 GPU 加速
            accelerator: true
        }
    });
}

async function startApp() {
    try {
        logTimeSince('Starting app');
        const backendPath = path.join(process.resourcesPath, 'backend');
        
        // 优化启动流程
        createMainWindow();
        logTimeSince('Main window created');

        // 启动后端服务
        splashWindow.webContents.send('startup-status', '正在启动服务...');
        await backendService.startBackend(backendPath);
        logTimeSince('Backend service started');
        
        // 检查后端服务和加载前端
        splashWindow.webContents.send('startup-status', '正在检查服务...');
        const backendStarted = await checkBackendService();
        if (!backendStarted) {
            log('Backend service failed to start');
            splashWindow.webContents.send('startup-failed');
            return;
        }

        splashWindow.webContents.send('startup-status', '正在加载应用...');
        mainWindow.loadURL('http://localhost:8000')
        
        mainWindow.once('ready-to-show', () => {
            mainWindow.show();
            splashWindow.close();
            logTimeSince('App fully loaded');
        });

        mainWindow.on('closed', () => {
            mainWindow = null;
        });

    } catch (error) {
        log(`Error in startApp: ${error}`);
        splashWindow.webContents.send('startup-failed');
    }
}

app.whenReady().then(() => {
    logTimeSince('App ready');
    createSplashWindow();
    startApp();

    // 处理重试请求
    require('electron').ipcMain.on('retry-startup', () => {
        startApp();
    });

    // 处理关闭请求
    require('electron').ipcMain.on('close-app', () => {
        app.quit();
    });

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            log('No windows found, creating new window...');
            createSplashWindow();
            startApp();
        }
    });
}).catch((error) => {
    log(`Error during app initialization: ${error}`);
});

app.on('window-all-closed', () => {
    log('All windows closed, quitting app...');
    app.quit();
});

// 确保应用退出时后端服务也被关闭
app.on('before-quit', async (event) => {
    if (!app.isQuitting) {
        event.preventDefault();
        log('App is quitting...');
        try {
            await backendService.stopBackend();
            app.isQuitting = true;
            app.quit();
        } catch (error) {
            log(`Error stopping backend: ${error}`);
            app.quit();
        }
    }
});

app.on('quit', () => {
    log('App has quit');
});

// 修改小票打印处理
ipcMain.handle('print-receipt', async (event, receipt) => {
  log(`Received print request: ${JSON.stringify(receipt)}`);

  try {
    const win = new BrowserWindow({
      width: 320,
      height: 500,
      show: true,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
      }
    });

    const templatePath = path.join(__dirname, 'receipt-template.html');
    log(`Loading template from: ${templatePath}`);

    // 等待页面加载完成
    await win.loadFile(templatePath);
    
    // 等待页面准备就绪
    await new Promise((resolve) => {
      win.webContents.once('did-finish-load', resolve);
    });
    
    // 传递数据到打印窗口
    win.webContents.send('receipt-data', receipt);
    log(`Sent receipt data to print window`);
    
    // 等待渲染完成
    await new Promise(r => setTimeout(r, 2000));

    // 获取打印机列表并验证
    const printers = await win.webContents.getPrintersAsync();
    const targetPrinter = printers.find(p => p.name === '小票打印机');
    
    if (!targetPrinter) {
        log('未找到小票打印机');
        win.close();
        return false;
    }
    
    log(`找到打印机: ${targetPrinter.name}`);

    // 修改打印选项，设置合适的纸张尺寸
    const options = {
        silent: false,
        printBackground: true,
        deviceName: targetPrinter.name,
        margins: {
            marginType: 'none',
        },
        pageSize: {
            width: 58000,
            height: 100000
        },
        scaleFactor: 100,
        landscape: false
    };

    // 使用 Promise 包装打印操作
    const printResult = await new Promise((resolve) => {
      win.webContents.print(options, (success, errorType) => {
        if (success) {
          log('打印成功');
          resolve(true);
        } else {
          log(`打印失败: ${errorType}`);
          resolve(false);
        }
      });
    });

    // 确保在返回结果之前关闭窗口
    win.close();
    return printResult;

  } catch (error) {
    log(`Print error: ${error.stack}`);
    throw error;
  }
});

// 修改标签打印处理
ipcMain.handle('print-label', async (event, label) => {
  log(`Received label print request: ${label}`);

  try {
    const win = new BrowserWindow({
      width: 400,
      height: 300,
      show: true,
      autoHideMenuBar: true,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
      }
    });

    const templatePath = path.join(__dirname, 'label-template.html');
    log(`Loading label template from: ${templatePath}`);

    await win.loadFile(templatePath);
    
    // 传递数据到打印窗口
    win.webContents.send('label-data', label);
    log(`Sent label data to print window`);
    // 获取打印机列表并验证
    const printers = await win.webContents.getPrintersAsync();
    const targetPrinter = printers.find(p => p.name === '标签打印机');

    if (!targetPrinter) {
        log('未找到标签打印机');
        win.close();
        return false;
    }
    // 指定打印机打印
    const options = {
    silent: false,
    printBackground: true,
    deviceName: targetPrinter.name,
    margins: {
        marginType: 'none',
    },

    pageSize: { width: 40000, height: 30000 },
    copies: 1
    }

    const result = await win.webContents.print(options);
    console.log('Print result:', result);
    return result;
  } catch (error) {
    log(`Label print error: ${error}`);
    log(`Error stack: ${error.stack}`);
    throw error;
  }
}); 